package cn.bqjr.eily.samples.common.shiro.filter;

import cn.bqjr.eily.samples.service.commom.IAuthService;
import cn.bqjr.eily.samples.service.commom.impl.AuthServiceImpl;
import cn.bqjr.eily.shiro.spring.boot.filter.AbstractAccessControlFilter;
import cn.bqjr.eily.utils.I18nUtils;
import cn.bqjr.eily.utils.SpringContextUtils;
import cn.bqjr.eily.utils.StringUtils;
import cn.bqjr.eily.web.exception.exclass.RequestException;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 验证码 过滤器
 */
public class VerifyCodeFilter extends AbstractAccessControlFilter {

    private IAuthService authService;
    private String verifyCodeParamName = null;
    private String verifyIdName = null;

    public VerifyCodeFilter(String name, String id) {
        this.verifyCodeParamName = name;
        this.verifyIdName = id;
    }

    @Override
    protected boolean doIsAccessAllowed(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Object o) {
        String verifyId = request.getHeader(verifyIdName);
        String verifyCode = request.getHeader(verifyCodeParamName);
        if (StringUtils.isNotEmpty(verifyId) && StringUtils.isNotEmpty(verifyCode)) {
            return getAuthService().checkVerifycode(verifyId, verifyCode);
        }
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest,
                                     ServletResponse servletResponse) throws Exception {
        throw new RequestException(I18nUtils.getMsg("error.request.inValidVerifyCode"));
    }

    private IAuthService getAuthService() {
        if (authService == null) {
            authService = SpringContextUtils.getBean(AuthServiceImpl.class);
        }
        return authService;
    }
}
